<template>
  <div>
    <a-tree
      v-if="showTree"
      class="draggable-tree"
      draggable
      :showLine="true"
      :showIcon="true"
      :loadData="onLoadData"
      :selectedKeys="selectedKeys"
      :defaultExpandedKeys="defaultExpandedKeys"
      :treeData="treeData"
      @select="onSelect"
      ref="tree"
    >
      <template #title="{ title }">
        <span>{{ title }}</span>
      </template>
    </a-tree>
  </div>
</template>

<script>
export default {
  data () {
    return {
      showTree: false,
      selectedKeys: [],
      defaultExpandedKeys: [],
      treeData: []
    }
  },
  mounted () {
    this.searchRoot()
  },
  methods: {
    generateTreeNode (data) {
      return {
        key: data.id,
        title: data.name,
        layer: data.layer
      }
    },
    searchRoot () {
      this.$http.post('/zg-system/org/root', {}, data => {
        const root = this.generateTreeNode(data)
        this.$http.get('/zg-system/org/next', { pid: root.key }, children => {
          root.children = children.map(t => {
            return this.generateTreeNode(t)
          })

          this.treeData = [root]
          this.defaultExpandedKeys = [root.key]
          this.showTree = true
          if (root.children.length > 0) {
            this.selectedKeys = [root.children[0].key]
            this.$emit('nodeClick', root.children[0])
          }
        })
      })
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        this.$http.get('/zg-system/org/next', { pid: treeNode.dataRef.key }, data => {
          treeNode.dataRef.children = data.map(t => {
            return this.generateTreeNode(t)
          })
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    onSelect (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      const node = info.node.dataRef
      // alert(JSON.stringify({
      //   key: node.key,
      //   title: node.title,
      //   layer: node.layer
      // }))
      this.$emit('nodeClick', {
        key: node.key,
        title: node.title,
        layer: node.layer
      })
    }

  }
}
</script>
<style lang="less" scoped>
</style>
